﻿#include "syncmanager.h"


SyncPoint SyncManager::generateUniqueSyncPoint()
{
    uint64_t id = next_id++;
    std::unique_lock<std::mutex> lock(id_mutex);
    std::shared_ptr<std::condition_variable> idstate = std::make_shared<std::condition_variable>();
    id_map.emplace(id, idstate);
    return id;
}

uint64_t SyncManager::waitForSyncPoint(SyncPoint syncPointId)
{
    std::unique_lock<std::mutex> lock(id_mutex);
    auto it = id_map.find(syncPointId);
    if (it != id_map.end()) {
        it->second->wait(lock);
    }
    uint64_t ret = response_map[syncPointId];
    response_map.erase(syncPointId);
    return ret;
}

void SyncManager::releaseSyncPoint(SyncPoint syncPointId, uint64_t id)
{
    std::unique_lock<std::mutex> lock(id_mutex);
    auto it = id_map.find(syncPointId);
    if (it != id_map.end()) {
        response_map.emplace(syncPointId, id);
        it->second->notify_all();
        id_map.erase(it);
    }
}

void SyncManager::stop()
{
    while(id_map.size()) {
        auto i = *id_map.begin();
        releaseSyncPoint(i.first, false);
    }
}
